package com.curlymaster.podcastalarmclock;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


//http://www.cbc.ca/podcasting/includes/hourlynews.xml
public class XmlReader {
	

	private String podcastUrl = "null";
	private BufferedReader fileReader;
	private String urlHeader = "      <enclosure url=";
	private File file ;
	private AndroidFileDownloader parentActivity;
	
	
	public XmlReader(AndroidFileDownloader inParentActivity)
	
	{
		parentActivity = inParentActivity;
		 file = new File((parentActivity.sdManager).getXmlFilePath());
		
		try {
			
			 fileReader = new BufferedReader( new FileReader(file));
	
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	public String getPodcastUrl()
	{
		findPodcastUrl();
		return podcastUrl;
		
	}
	
	
	private void findPodcastUrl()
	{
		
		String currentLine;

		boolean isFound = false;
		
	
	try{
		
		//find the url of the mp3 file inside the xml file
		while ((currentLine = fileReader.readLine()) != null && !isFound)
		{
       
			//read only a certain line of a specific length
			if((currentLine.length() > 128) && (currentLine.contains(urlHeader))) ///// HARD CODING
			{
				
				isFound = true;
				
				boolean beginningFound = false;
				boolean endingFound = false;
				int beginPos,endingPos;
				
				// go through the string to find the 2 ' " ' to know where the path starts and finish
				for(beginPos = 0; (beginPos<currentLine.length()) && (!beginningFound)  ; beginPos++)
				{
					if(currentLine.charAt(beginPos)=='"' && !beginningFound)
					{
						beginningFound = true;
					}
				}	
				for(endingPos = beginPos; (endingPos<currentLine.length()) && (!endingFound)  ; endingPos++)
				{
					if(currentLine.charAt(endingPos) == '"' && !endingFound)
					{
						endingFound = true;
					}
				}
				
				podcastUrl=currentLine.substring(beginPos,endingPos-1);
				

			}
		}
		
		
	}	
	catch (IOException e) {
	    //You'll need to add proper error handling here
	}
	
	}
	
	public void close()
	{
		try {
			fileReader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
